<template>
  <div class="menu_container">
    <el-checkbox
      v-model="menuExpand"
      @change="handleCheckedTreeExpand($event, 'menu')"
      >展开/折叠</el-checkbox
    >
    <el-checkbox
      v-model="menuNodeAll"
      @change="handleCheckedTreeNodeAll($event, 'menu')"
      >全选/全不选</el-checkbox
    >
    <el-checkbox
      v-model="form.menuCheckStrictly"
      @change="handleCheckedTreeConnect($event, 'menu')"
      >父子联动</el-checkbox
    >
    <el-button
      type="cyan"
      size="mini"
      @click="handleSaveMenu"
      v-hasPermi="['system:privileg:save']"
      >保存</el-button
    >
    <el-tree
      class="tree-border"
      :data="menuOptions"
      show-checkbox
      ref="menu"
      node-key="menuId"
      :check-strictly="!form.menuCheckStrictly"
      empty-text="加载中，请稍后"
      :props="defaultProps"
    ></el-tree>
  </div>
</template>

<script>
import {
  listMenu as menuTreeselect,
  roleMenuTreeselect,
} from "@/api/system/menu";
import {
  savePrivilegeConfig, //部分栏目  或者站点
} from "@/api/system/userGroup";
import { mapState } from "vuex";
export default {
  props: {
    SysSubMenu: {},
  },
  data() {
    return {
      menuOptions: [],
      deptOptions: [],
      form: {
        menuCheckStrictly: true,
      },
      defaultProps: {
        children: "children",
        label: "menuName",
      },
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      //选中的菜单
      checkRowKeysmenuIds: [],
    };
  },

  components: {},

  computed: { ...mapState(["column"]) },
  created() {},
  mounted() {
    this.getMenuTreeselect();
    this.$nextTick(() => {});
  },

  watch: {
    value: {
      handler(val) {},
      deep: true,
      immediate: true,
    },
  },

  methods: {
    /** 查询菜单树结构 */
    getMenuTreeselect() {
      menuTreeselect()
        .then((response) => {
          this.menuOptions = this.handleTree(
            response.data.filter(
              (item) => item.menuType != "F" && item.status == 0
            ),
            "menuId"
          );
        })
        .then(() => {
          this.$nextTick(() => {
            this.checkedmenuIdKeys();
          });
        });
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      if (type == "menu") {
        let treeList = this.menuOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.menu.store.nodesMap[treeList[i].menuId].expanded = value;
        }
      } else if (type == "dept") {
        let treeList = this.deptOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.dept.store.nodesMap[treeList[i].id].expanded = value;
        }
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      this.$nextTick(() => {});
      if (type == "menu") {
        this.$refs.menu.setCheckedNodes(value ? this.menuOptions : []);
      } else if (type == "dept") {
        this.$refs.dept.setCheckedNodes(value ? this.deptOptions : []);
      }
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value, type) {
      if (type == "menu") {
        this.form.menuCheckStrictly = value ? true : false;
      } else if (type == "dept") {
        this.form.deptCheckStrictly = value ? true : false;
      }
    },
    //保存选中的菜单
    handleSaveMenu() {
      this.menuIds = this.getMenuAllCheckedKeys();
      Promise.all([
        //保存主菜单
        new Promise((resolve) => {
          if (
            this.menuIds.SysMainMenu.length == 0 &&
            this.menuIds.SysSubMenu.length == 0
          ) {
            this.msgError("菜单不能为空");
            return;
          }
          savePrivilegeConfig({
            functionIdStr: this.menuIds.SysMainMenu.join(","),
            groupId: this.column.userGroupRow.groupId,
            type: "SysMainMenu",
          }).then((res) => {
            resolve(res);
          });
        }),
        //保存按钮菜单
        new Promise((resolve, reject) => {
          // if (this.menuIds.SysSubMenu.length == 0) {
          //   this.msgError("菜单不能为空");
          //   return;
          // }
          savePrivilegeConfig({
            functionIdStr: this.menuIds.SysSubMenu.join(","),
            groupId: this.column.userGroupRow.groupId,
            type: "SysSubMenu",
          }).then((res) => {
            resolve(res);
          });
        }),
      ])
        .then((res) => {
          this.$emit("getGroupInitPrivilege");
          this.msgSuccess("保存成功");
        })
        .catch((e) => {
          this.msgError("保存失败");
        });
      // savePrivilegeConfig({
      //   functionIdStr: this.cloumnIds,
      //   groupId: this.column.userGroupRow.groupId,
      //   type: "Channel",
      // }).then((res) => {
      //   if (res.code == 200) {
      //     this.$emit("getGroupInitPrivilege");
      //     this.msgSuccess("保存成功");
      //   }
      // });
    },
    // // 所有菜单节点数据
    // getMenuAllCheckedKeys() {
    //   // 目前被选中的菜单节点
    //   let checkedKeys = this.$refs.menu.getCheckedKeys();
    //   // 半选中的菜单节点
    //   let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
    //   checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
    //   return checkedKeys;
    // },。

    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      let SysMainMenu = [];
      let SysSubMenu = [];
      let checkedNodes = this.$refs.menu.getCheckedNodes();
      let getHalfCheckedNodes = this.$refs.menu.getHalfCheckedNodes();
      checkedNodes.concat(getHalfCheckedNodes).map((item) => {
        if (item.menuType == "M") {
          SysMainMenu.push(item.menuId);
        } else if (item.menuType == "C") {
          SysSubMenu.push(item.menuId);
        }
      });

      return { SysMainMenu, SysSubMenu };
    },
    setCheckedKeys() {
      this.$refs.tree.setCheckedKeys([3]);
    },
    checkedmenuIdKeys() {
      let checkedKeys = this.SysSubMenu;
      let arr = [];

      checkedKeys.forEach((v) => {
        arr.push(v.functionId);
        this.$nextTick(() => {
          this.$refs.menu.setChecked(v.functionId, true, false);
        });
      });
      this.checkRowKeysmenuIds = arr;
    },
  },
};
</script>

<style scoped lang="scss">
.menu_container {
  height: 100%;
}
</style>
